package com.example.itshome.network;

import android.app.Activity;
import android.widget.Toast;
import com.example.itshome.manager.UserInfoManager;
import com.example.itshome.util.ToastUtil;
import org.json.JSONException;
import org.json.JSONObject;

public class ChangePasswordRequest extends AbstractNetworkRequest{
    private String oldPassword;
    private String newPassword;
    private String newPasswordConfirm;

    public ChangePasswordRequest setOldPassword(String oldPassword) {
        this.oldPassword = oldPassword;
        return this;
    }

    public ChangePasswordRequest setNewPassword(String newPassword) {
        this.newPassword = newPassword;
        return this;
    }

    public ChangePasswordRequest setNewPasswordConfirm(String newPasswordConfirm) {
        this.newPasswordConfirm = newPasswordConfirm;
        return this;
    }

    public ChangePasswordRequest(Activity activity) {
        super(activity,POST_METHOD);
    }

    @Override
    protected String getPathAndParams() {
        return "user/change-pwd?username="+ UserInfoManager.getInstance().getUser().getUsername() +
                "&oldPassword="+oldPassword+"&newPassword="+newPassword;
    }

    @Override
    protected void handleResult(String result) {
        try {
            JSONObject jsonObject=new JSONObject(result);
            int code =jsonObject.getInt("code");
            if(code==200){
                setHandleResultRunnable(new Runnable() {
                    @Override
                    public void run() {
                        ToastUtil.showToast("修改成功",activity);
                        activity.finish();
                    }
                });
            }else if(code==106){
                setHandleResultRunnable(new Runnable() {
                    @Override
                    public void run() {
                        ToastUtil.showToast("旧密码错误",activity);
                    }
                });
            }

        }catch (JSONException e){
            e.printStackTrace();
        }

    }

    @Override
    protected boolean canStart() {
        if(!newPassword.equals(newPasswordConfirm)){
            Toast.makeText(activity,"两次输入的不一样",Toast.LENGTH_SHORT).show();
            return false;
        }
        return true;
    }
}
